<?php
/*
 * 缩略图上传类
 * @author     Mark <zhaody901@126.com>
 * @copyright  Copyright (c) 2013 lemon team
 * @version    $Id: 42c979093ddb76e06546809f3d78ef4320a2410e $
 * @time       14-1-22 下午3:23
 */
class ThumbUpload extends PictureUpload {

	/** @var 图片宽度 */
	protected $width;

	/** @var 图片高度 */
	protected $height;


	protected function _checkAll(){
		parent::_checkAll();
		// setting
		if (!$this->width || !$this->height) {
			$this->setErr(self::ERR_SETTING_LOST);
			return false;
		}
		return true;
	}

	public function setSize($width = 0, $height = 0) {
		// 有宽度, 计算高度
		if ($width && !$height) {
			$height = $width * (2 / 3);
		}

		// 有高度, 计算宽度
		if ($height && !$width) {
			$width = $height * (3 / 2);
		}

		$this->width  = $width;
		$this->height = $height;
	}

	public function save($file) {
		if (parent::save($file)) {
			$this->url = Picture::thumb(Picture::url($this->aimPath), $this->width, $this->height);
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 清空需要存储的URL
	 * @param $sessionGroup
	 * @param $new_url
	 * @param $old_url
	 * @param $userid
	 */
	public static function clearPicture($sessionGroup, $new_url, $old_url, $userid) {
		$new_urls = !is_array($new_url) ? (array) $new_url : $new_url ;
		$old_urls = !is_array($old_url) ? (array) $old_url : $old_url ;

		$old_urls = array_map(array('Picture', 'basename'), $old_urls);
		$new_urls = array_map(array('Picture', 'basename'), $new_urls);

		$diff_urls = array();
		// old not in
		foreach($old_urls as $url) {
			if (!in_array($url, $new_urls)) $diff_urls[] = Picture::basename($url);
		}

		// new not in
		$files = self::getSession($sessionGroup);

		foreach($files as $item) {
			if (!in_array(Picture::basename($item['url']), $new_urls)) {
				$diff_urls[] = Picture::basename($item['url']);
			}
		}

		// del not need del and session
		foreach ($diff_urls as $url) {
			self::deletePicture($url, $userid);
			self::clearPictureSession(Picture::basename($url));
		}

		// url not used
		foreach($new_urls as $url) {
			self::clearPictureSession(Picture::basename($url));
		}

	}

	/**
	 * 错误提示
	 */
	public function error() {
		exit(json_encode(array('errNo' => $this->errno, 'errMsg' => $this->error)));

	}

	/**
	 * 成功, 返回URL地址
	 */
	public function ok() {
		exit(json_encode(array('errNo' => self::ERR_OK, 'url' => $this->url)));
	}
}